<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <search :config="searchConfig" @search="search" @getHeight="getHeight"/>
    <!-- table区域-begin -->
    <div class="page_table">
      <vxe-grid
        ref="xGrid"
        :border="true"
        :resizable="true"
        :showOverflow="true"
        size="mini"
        :loading="loading"
        :height="pageHeight-seachHeight-94"
        :align="left"
        :columns="columns"
        :data="dataSource"
        :toolbar-config="tableToolbar"
        :checkbox-config="checkboxConfig"
        v-bind="vexConfig"
        @checkbox-change="selectChangeEvent"
        @checkbox-all="selectChangeEvent"
      >
        <template #toolbar_buttons>
          <!-- 操作按钮区域 -->
          <div class="table-operator">
            <a-button @click="handleAdd" type="primary" v-has="'ordermgt:add'">新增</a-button>
            <a-button v-has="'ordermgt:commit'" type="primary" @click="handleSubmit">提交</a-button>
            <a-button type='primary' @click='handleAppdatarove' :disabled="selectionRows.length!=1||selectionRows[0].orderStatus!=40">审批</a-button>
            <a-button v-has="'ordermgt:delete'" @click="batchDel">删除</a-button>
            <a-button v-has="'ordermgt:recall'" @click="pullback()">撤回</a-button>
            <a-button v-has="'ordermgt:pushSap'" @click="handlePush">推送SAP</a-button>
            <a-button v-has="'ordermgt:pushOms'" @click="handlePushOms">推送OMS</a-button>
            <a-button v-has="'ordermgt:carpooling'" @click="carpooling()">拼车</a-button>
            <a-button v-has="'ordermgt:cancellation'" @click="cancellation()">合同作废</a-button>
            <!--      <a-button type="primary" @click="downExportXls('cnProduct_service')">同步</a-button>-->
            <a-button v-has="'ordermgt:export'" @click="downExportXls('order_manage' )">导出</a-button>
          </div>
        </template>
        <template #detail="{ row,rowIndex }">
          <a @click="handleDetaila(row)">{{ row.orderCode }}</a>
        </template>
<!--        <template #omsOrderCode="{ row,rowIndex }">-->
<!--          <a style="color: green" @click="OmsDetaila(row)">{{ row.omsOrderCode }}</a>-->
<!--        </template>-->
        <template #getStatus="{ row,rowIndex }">
          {{ filterDictText(statusList, row.orderStatus) }}
        </template>
        <template #dataSource="{ row,rowIndex }">
          {{ filterDictText(sourceList, row.dataSource) }}
        </template>
        <template #isPushOms="{ row,rowIndex }">
          <div v-if="row.isPushOms=='Y'">是</div>
          <div v-if="row.isPushOms=='N'">否</div>
        </template>
        <template #isPushSap="{ row,rowIndex }">
          <div v-if="row.isPushSap=='Y'">是</div>
          <div v-if="row.isPushSap=='N'">否</div>
        </template>
        <template #updateStatus="{ row,rowIndex }">
          <a-switch :checked="row.status==1" size="small" :value="row" @change="changeStatus($event,row)"/>
        </template>
        <template #action="{ row }">
          <a v-if="['10','20'].includes(row.orderStatus)" v-has="'ordermgt:update'" @click="handleEdit(row)">编辑</a>
          <a v-if="row.orderStatus=='40' && row.orderType=='ZO10'&&row.isCarpooling!='C'" v-has="'ordermgt:update'" @click="handleEdit(row)">编辑</a>
          <a-divider type="vertical" v-if="['10','20'].includes(row.orderStatus)||(row.orderStatus=='40'&&row.orderType=='ZO10')"/>
          <a href="javascript:;" @click='handleBusiness("订单管理",row)'>日志</a>
        </template>
        <template #pager>
          <vxe-pager
            :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
            :currentPage.sync="ipagination.current"
            :page-size.sync="ipagination.pageSize"
            :total="ipagination.total"
            :pageSizes="ipagination.pageSizeOptions"
            @page-change="handlePageChange">
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>
    <ordermgtModal ref="modalForm" @ok="modalFormOk"></ordermgtModal>
<!--    <orderOMSModal ref="orderOMSForm" @ok="modalFormOk"></orderOMSModal>-->
    <carpooling-modal ref="carpoolingForm" @ok="modalFormOk"></carpooling-modal>
    <business-log ref="businessLog"></business-log>
  </a-card>
</template>

<script>
import ordermgtModal from './TerminalOrderModal/ordermgtModal.vue'
import CarpoolingModal from '@views/mdm/order-center/TerminalOrderModal/CarpoolingModal'
// import orderOMSModal from './TerminalOrderModal/orderOMSModal.vue'
import { PageListMixin } from '@/mixins/PageListMixin'
import { getAction, postAction } from '@api/manage'
import Vue from 'vue'
import { initDictOptions, filterDictText } from '@comp/dict/CnDictSelectUtil'

export default {
  name: 'userorgerl',
  mixins: [PageListMixin],
  components: {
    ordermgtModal,
    // orderOMSModal,
    CarpoolingModal
  },
  data() {
    return {
      selectedRowKeys: [],
      description: '订单管理',
      searchConfig: [
        {
          // label:'区域编号',
          type: 'input',
          name: 'orderCode',
          placeholder: '订单编号',
        },
        {
          type: 'j-select',
          name: 'orderType',
          placeholder: '订单类型',
          dictCode:'order_type',
        },
        {
          type: 'input',
          name: 'customerCode',
          placeholder: '客户编号'
        },
        {
          type: 'input',
          name: 'customerName',
          placeholder: '客户名称'
        },
        {
          type: 'input',
          name: 'originalCode',
          placeholder: '原始单据号'
        },
        // {
        //   type: 'input',
        //   name: 'carpoolingCode',
        //   placeholder: '拼车单号'
        // },
        // {
        //   type: 'j-select',
        //   name: 'isCarpooling',
        //   placeholder: '拼车状态',
        //   dictCode: 'carpooling_state',
        // },
        {
          type: 'date-range',
          range: ['expectedDeliveryDateBegin', 'expectedDeliveryDateEnd'],
          name: 'expecteds',
          placeholder: ['预计到货日期', '预计到货日期']
        },
        {
          type: 'date-range',
          range: ['createTimeBegin', 'createTimeEnd'],
          name: 'creates',
          placeholder: ['订单创建时间', '订单创建时间']
        },
        {
          type: 'j-select',
          name: 'orderStatus',
          placeholder: '请选择订单状态',
          dictCode: 'dms_order_data_status'
        },
      ],
      //表头
      columns: [],
      //列设置
      settingColumns: [],
      defColumns: [
        { type: 'checkbox', width: 60, fixed: 'left' },
        {
          title: '订单编号',
          align: 'left',
          field: 'orderCode',
          fixed: 'left',
          minWidth: 100,
          slots: { default: 'detail' }
        },
        {
          title: '原始单据号',
          align: 'left',
          field: 'originalCode',
          fixed: 'left',
          minWidth: 100,
        },
        // {
        //   title: 'OMS订单号',
        //   align: 'left',
        //   field: 'omsOrderCode',
        //   minWidth: 100,
        //   // slots: { default: 'omsOrderCode' }
        // },
        // {
        //   title: 'SAP合同号',
        //   align: 'left',
        //   field: 'sapContractCode',
        //   minWidth: 100,
        // },
        // {
        //   title: '拼车单号',
        //   align: 'left',
        //   field: 'carpoolingCode',
        //   minWidth: 100,
        // },
        // {
        //   title: '拼车状态',
        //   align: 'left',
        //   field: 'isCarpoolingDesc',
        //   minWidth: 100,
        // },
        {
          title: '订单类型',
          align: 'left',
          field: 'orderTypeDesc',
          minWidth: 100,
        },
        {
          title: '客户编号',
          align: 'left',
          field: 'customerCode',
          minWidth: 100,
        },
        {
          title: '客户名称',
          align: 'left',
          field: 'customerName',
          minWidth: 120,
        },
        {
          title: '所属组织',
          align: 'left',
          field: 'custOpOrgName',
          minWidth: 100,
        },
        {
          title: '订单金额',
          align: 'left',
          field: 'originalPriceTotal',
          minWidth: 80,
        },
        {
          title: '结算金额',
          align: 'left',
          field: 'totalPayAmount',
          minWidth: 80,
        },
        {
          title: '订单来源',
          align: 'left',
          field: 'dataSourceDesc',
          minWidth: 80,
          // slots: { default: 'dataSource' }
        },
        {
          title: '预计到货日期',
          align: 'left',
          field: 'expectedDeliveryDate',
          minWidth: 120,
        },
        // {
        //   title: '是否推送SAP',
        //   align: 'left',
        //   field: 'isPushSap',
        //   minWidth: 120,
        //   slots: { default: 'isPushSap' }
        // },
        // {
        //   title: '是否推送OMS',
        //   align: 'left',
        //   field: 'isPushOms',
        //   minWidth: 120,
        //   slots: { default: 'isPushOms' }
        // },
        {
          title: '创建人',
          align: 'left',
          minWidth: 80,
          field: 'createName'
        },
        {
          title: '创建时间',
          align: 'left',
          minWidth: 80,
          field: 'createTime'
        },
        {
          title: '更新人',
          align: 'left',
          minWidth: 80,
          field: 'updateName'
        },
        {
          title: '更新时间',
          align: 'left',
          minWidth: 80,
          field: 'updateTime'
        },
        // {
        //   title: 'OMS订单状态',
        //   align: 'left',
        //   field: 'omsOrderStatus',
        //   fixed: 'right',
        //   minWidth: 100,
        //   // slots: { default: 'getStatus' }
        // },
        {
          title: '订单状态',
          align: 'left',
          field: 'orderStatus',
          fixed: 'right',
          minWidth: 80,
          slots: { default: 'getStatus' }
        },
        {
          title: '操作',
          field: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 100,
          slots: {
            default: 'action'
          }
        }
      ],
      isorter: {
        permflag: 'order_page_impl'
      },
      statusList: [],
      sourceList: [], // 订单来源字典
      url: {
        list: window._CONFIG['domianDmsURL'] + '/order/dmsOrderHead/findPageList',
        detail: window._CONFIG['domianDmsURL'] + '/order/dmsOrderHead/findOrderInfo',
        edit: window._CONFIG['domianDmsURL'] + '/order/dmsOrderHead/findOrderChangeInfo',
        cancellation: window._CONFIG['domianDmsURL'] + '/order/dmsOrderHead/sapContractClose',
        orderClose: window._CONFIG['domianDmsURL'] + '/order/dmsOrderHead/omsVoidOrder',
        push: window._CONFIG['domianDmsURL'] + '/order/dmsOrderHead/sapContractCreate',
        pushOms: window._CONFIG['domianDmsURL'] + '/order/dmsOrderHead/omsOrderCreate',
        carpooling: window._CONFIG['domianDmsURL'] + '/order/dmsOrderHead/findOrderCarpoolingInfo',
        submit:window._CONFIG['domianDmsURL'] + '/order/dmsOrderHead/submitOrderList',
        deleteBatch:window._CONFIG['domianDmsURL'] + '/order/dmsOrderHead/deleteBatch',
        // delete: window._CONFIG['domianURL'] + '/userorgrelation/cnUserOrgRelation/delete',
        // exportXlsUrl: window._CONFIG['domianTpmURL'] + 'budget/tpmBudgetFee/exportXls'
      }
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  created() {
    this.initColumns()
  },
  methods: {
    filterDictText,
    initDictConfig() {
      console.log('--我才是真的方法!--')
      initDictOptions('order_source').then((res) => {
        if (res.success) {
          this.sourceList = res.result
        }
      })
      initDictOptions('dms_order_data_status').then((res) => {
        if (res.success) {
          this.statusList = res.result
        }
      })
    },
    handleAppdatarove: async function(record, status) {
      if (this.selectedRowKeys.length != 1) {
        this.$message.warning('请选择一条记录！')
        return
      }
      console.log(this.selectionRows)
      let that = this
      // that.loading = true
      let cods = JSON.parse(JSON.stringify(record))
      const res = await postAction(this.url.detail, { id: that.selectedRowKeys + '' })
      if (res.success) {
        record = res.result
        record.bpmStatus = 4
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '审批'
        this.$refs.modalForm.disableSubmit = true
        this.$refs.modalForm.saveButton = false
        this.$refs.modalForm.orgContral = true
        this.$refs.modalForm.appdata=true
      } else {
        this.$message.error(res.message)
      }
    },
    handleSubmit() {
      let list = this.selectionRows.filter(item => item.orderStatus == '20').map(val => val.orderCode)
      if (!list.length) {
        this.$message.info('没有可提交的数据（只能提交KA待提交订单）')
        return
      }
      var that = this
      this.$confirm({
        title: '确认提交',
        content: `是否提交选中的${list.length}条KA待提交订单?`,
        onOk: function () {
          that.loading = true
          postAction(that.url.submit, { orderCodeList: list }).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.loading = false
          })
        }
      })
    },
    async carpooling() {
      let record = {}
      if (this.url.carpooling) {
        const res = await postAction(this.url.carpooling, { orderIds: this.selectedRowKeys })
        if (res.success) {
          if (res.result) {
            record = res.result
          }
        } else {
          this.$message.error(res.message)
          return
        }
      }
      this.$refs.carpoolingForm.edit(record)
      this.$refs.carpoolingForm.title = '合并拼车'
      this.$refs.carpoolingForm.disableSubmit = false
    },
    pullback() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else if (this.selectedRowKeys.length > 1) {
        this.$message.warning('只能每次撤回一条数据！')
        return
      } else {
        var that = this
        this.$confirm({
          title: '确认撤回',
          content: `是否撤回${that.selectionRows[0].orderCode}订单?`,
          onOk: function () {
            that.loading = true
            postAction(that.url.orderClose, { fromOrderNo: that.selectionRows[0].orderCode }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.loading = false
            })
          }
        })

      }
    },
    handlePush() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else if (this.selectedRowKeys.length > 1) {
        this.$message.warning('只能每次作废一条数据！')
        return
      } else {
        var that = this
        this.$confirm({
          title: '确认推送',
          content: `是否推送订单${that.selectionRows[0].orderCode}数据到SAP?`,
          onOk: function () {
            that.loading = true
            getAction(that.url.push, { orderCode: that.selectionRows[0].orderCode }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.loading = false
            })
          }
        })

      }
    },
    handlePushOms() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else if (this.selectedRowKeys.length > 1) {
        this.$message.warning('只能每次作废一条数据！')
        return
      } else {
        var that = this
        this.$confirm({
          title: '确认推送',
          content: `是否推送订单${that.selectionRows[0].orderCode}数据到OMS?`,
          onOk: function () {
            that.loading = true
            getAction(that.url.pushOms, { orderCode: that.selectionRows[0].orderCode }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.loading = false
            })
          }
        })

      }
    },
    cancellation() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else if (this.selectedRowKeys.length > 1) {
        this.$message.warning('只能每次作废一条数据！')
        return
      } else {
        var that = this
        this.$confirm({
          title: '确认作废',
          content: `是否作废订单${that.selectionRows[0].orderCode}数据?`,
          onOk: function () {
            that.loading = true
            getAction(that.url.cancellation, { orderCode: that.selectionRows[0].orderCode }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.loading = false
            })
          }
        })

      }
    },
    //列表设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.field == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.field)) {
          return true
        }
        return false
      })
      this.columns = cols
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    changeStatus(e, item) {
      if (e) {
        this.startorstopByid(1, item.id)
      } else {
        this.startorstopByid(0, item.id)
      }
    },
    startorstopByid(status, id) {
      let that = this
      this.$confirm({
        title: '确认修改',
        content: '是否' + (status == 0 ? '停用' : '启动') + '选中数据？',
        onOk() {
          that.loading = true
          getAction(that.url.startOrStopUrl, { ids: id, status: status }).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
              that.onClearSelected()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.loading = false
          })
        },
        onCancel() {
          // that.loadData();
          // that.onClearSelected();
        },
      })
    },
    // 编辑
    handleEdit: async function (record) {
      // if (this.url.edit) {
      //   const res = await postAction(this.url.edit, { id: record.id })
      //   if (res.success) {
      //     if (res.result) {
      //       record = res.result
      //     }
      //   } else {
      //     this.$message.error(res.message)
      //   }
      // }
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.disableSubmit = false
    },
    handleDetaila: async function (record) {
      const modal = this.$refs.modalForm
      modal.edit(record, 'detail')
      modal.title = '详情'
      modal.disableSubmit = true
    },
    OmsDetaila: async function (record) {
      const modal = this.$refs.orderOMSForm
      modal.edit(record, 'detail')
      modal.title = '订单详情'
      modal.disableSubmit = true
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = []
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.field)
        })
        this.settingColumns = allSettingColumns
        this.columns = this.defColumns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.field == 'action') {
            return true
          }
          if (colSettings.includes(item.field)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    },
  }
}
</script>

<style scoped>
@import '~@assets/less/common.less';
</style>